import json
import os
from typing import Dict, List, Optional, Any
import fnmatch
import logging

logger = logging.getLogger(__name__)

class RuleManager:
    """规则管理器 - 负责加载和匹配抓取规则"""
    
    def __init__(self, rules_dir: str = "rules"):
        self.rules_dir = rules_dir
        self.rules: List[Dict[str, Any]] = []
        self.load_all_rules()
    
    def load_all_rules(self) -> None:
        """加载所有规则文件"""
        self.rules.clear()
        
        if not os.path.exists(self.rules_dir):
            logger.warning(f"规则目录不存在: {self.rules_dir}")
            return
        
        for filename in os.listdir(self.rules_dir):
            if filename.endswith('.json') and filename != 'example_news.json':
                rule_path = os.path.join(self.rules_dir, filename)
                try:
                    with open(rule_path, 'r', encoding='utf-8') as f:
                        rule = json.load(f)
                        
                        # 检查enable字段，只加载启用的规则
                        enable_value = rule.get('enable', 'true')  # 默认为启用
                        if enable_value == 'true' or enable_value is True:
                            rule['_filename'] = filename
                            self.rules.append(rule)
                            logger.info(f"加载规则: {rule.get('name', filename)}")
                        else:
                            logger.info(f"跳过已禁用的规则: {rule.get('name', filename)}")
                except Exception as e:
                    logger.error(f"加载规则文件失败 {filename}: {e}")
    
    def reload_rules(self) -> None:
        """重新加载所有规则（手动刷新规则缓存）"""
        logger.info("重新加载规则文件...")
        self.load_all_rules()
    
    def find_matching_rule(self, url: str) -> Optional[Dict[str, Any]]:
        """根据URL找到匹配的规则"""
        for rule in self.rules:
            url_pattern = rule.get('url_pattern', '')
            
            # 支持通配符匹配
            if fnmatch.fnmatch(url, url_pattern) or url.startswith(url_pattern.rstrip('*')):
                logger.info(f"找到匹配规则: {rule.get('name')} for {url}")
                return rule
        
        logger.warning(f"未找到匹配的规则: {url}")
        return None
    
    def get_all_rules(self) -> List[Dict[str, Any]]:
        """获取所有规则"""
        return self.rules.copy()
    
    
    def list_rules(self) -> List[Dict[str, str]]:
        """列出所有规则的基本信息"""
        rule_list = []
        for rule in self.rules:
            rule_list.append({
                'filename': rule.get('_filename'),
                'name': rule.get('name'),
                'url_pattern': rule.get('url_pattern'),
                'category': rule.get('metadata', {}).get('category', '未分类')
            })
        return rule_list